package com.rpinfo.editalog.util;

import com.rpinfo.editalog.config.Cfg;
import com.rpinfo.editalog.config.CfgPropUtil;
import com.rpinfo.editalog.venda.Fin;
import com.rpinfo.editalog.venda.Vit;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
 *
 * @author camilo
 */
public class HibernateUtil {

  private static final SessionFactory factory;
  private static final ServiceRegistry registry;
  private static final Fin fin = new Fin();
  private static final Vit vit = new Vit();

  static {
    Configuration cfg = new Configuration();

    CfgPropUtil propUt = new CfgPropUtil();
    Cfg prop = propUt.getCfgProp();
    cfg.setProperty("hibernate.connection.url",
            "jdbc:postgresql://" + prop.getIp() + ":" + prop.getPorta() + "/" + prop.getNomeBd());
    cfg.setProperty("hibernate.connection.username", prop.getUser());
    cfg.setProperty("hibernate.connection.password", prop.getPassword());
    cfg.setProperty("hibernate.current_session_context_class", "thread");
    cfg.setProperty("hibernate.hbm2ddl.auto", "update");
    cfg.setProperty("show_sql", "true");
    cfg.setProperty("format_sql", "true");
    cfg.setProperty("generate_statistics", "false");
    cfg.setProperty("use_sql_comments", "false");

    cfg.addAnnotatedClass(fin.getClass());
    cfg.addAnnotatedClass(vit.getClass());
    
    registry
            = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
    factory = cfg.buildSessionFactory(registry);
  }

  public static SessionFactory getSessionFactory() {

    return factory;
  }

  public static void IniciaConexao(Transaction transacao, Session session) {
    transacao = session.beginTransaction();
  }

  public static void Commit(Transaction transacao) {
    transacao.commit();
  }
}
